#include <iostream>
#include <memory>
#include <unistd.h>
#include "protocol.pb.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/net/TcpClient.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"
#include "muduo/base/Logging.h"

class Client
{
private:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<protocol::AddResponse> AddResponsePtr;
    typedef std::shared_ptr<protocol::TranslateResponse> TranslateResponsePtr;

private:
    void onKnownMessage(const muduo::net::TcpConnectionPtr& conn,const MessagePtr& message,muduo::Timestamp)
    {
        LOG_INFO<<"onKnownMessage: "<<message->GetTypeName();
        conn->shutdown();
    }

    void onTranslate(const muduo::net::TcpConnectionPtr& conn,const TranslateResponsePtr& message,muduo::Timestamp)
    {
        std::cout<<"翻译结果: "<<message->message()<<std::endl;
    }

    void onAdd(const muduo::net::TcpConnectionPtr& conn,const AddResponsePtr& message,muduo::Timestamp)
    {
        std::cout<<"加法结果: "<<message->result()<<std::endl;
    }

    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected()==true)
        {
            _latch.countDown();//唤醒在条件变量上等待的线程
            _conn=conn;
            LOG_INFO<<"新连接建立成功";
        }
        else
        {
            _conn.reset();
            LOG_INFO<<"连接关闭";
        }
    }

    bool send(const google::protobuf::Message& message)
    {
        if(_conn->connected()==true)
        {
            _codec.send(_conn,message);
            return true;
        }
        return false;
    }

public:
    Client(const std::string& ip="127.0.0.1",uint16_t port=8080)
        :_latch(1)
        ,_client(_loop_thread.startLoop(),muduo::net::InetAddress(ip,port),"client")
        ,_dispatcher(std::bind(&Client::onKnownMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3))
        ,_codec(std::bind(&ProtobufDispatcher::onProtobufMessage,&_dispatcher,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3))
    {
        //给分发器_dispatcher设置回调函数
        _dispatcher.registerMessageCallback<protocol::TranslateResponse>(std::bind(&Client::onTranslate,this,std::placeholders::_1,
                                                                std::placeholders::_2,std::placeholders::_3));
        _dispatcher.registerMessageCallback<protocol::AddResponse>(std::bind(&Client::onAdd,this,std::placeholders::_1,
                                                                std::placeholders::_2,std::placeholders::_3));
        
        //给客户端_client设置回调函数
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage,&_codec,std::placeholders::_1,
                                                                std::placeholders::_2,std::placeholders::_3));
        _client.setConnectionCallback(std::bind(&Client::onConnection,this,std::placeholders::_1));
    }

    void client()
    {
        _client.connect();//不是立即连接就建立成功的，需要等待建立成功
        _latch.wait();
    }

    void translate(const std::string& str)
    {
        protocol::TranslateRequest res;
        res.set_message(str);
        send(res);
    }

    void add(int num1,int num2)
    {
        protocol::AddRequest res;
        res.set_num1(num1);
        res.set_num2(num2);
        send(res);
    }

    ~Client()=default;

private:
    muduo::CountDownLatch _latch;//互斥+条件变量
    muduo::net::EventLoopThread _loop_thread;//线程EventLoop
    muduo::net::TcpConnectionPtr _conn;//请求建立之后成功的连接
    muduo::net::TcpClient _client;//客户端
    ProtobufDispatcher _dispatcher;//业务分发器
    ProtobufCodec _codec;//业务处理器
};

int main()
{
    std::unique_ptr<Client> ptr(new Client());
    ptr->client();
    ptr->translate("hello");
    ptr->add(1,2);
    sleep(5);
    return 0;
}